package com.zzyl.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @version 1.0
 * @description 说明：针对小程序端的
 * @package com.zzyl.framework.interceptor
 */
@Component
@Slf4j
@AllArgsConstructor
public class MemberInterceptor implements HandlerInterceptor {

    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            // controller方法的则放行
            return true;
        }
        //获取请求头中的token
        String token = request.getHeader("authorization");
        //判断并解析token
        if(StrUtil.isNotEmpty(token)) {
            //获取登录用户的id
            try {
                Claims claims = tokenService.parseToken(token);
                Long memberId = claims.get("userId", Long.class);
                // 存入ThreadLocal
                UserThreadLocal.set(memberId);
                return true;
            } catch (Exception e) {
                // token是假的，过期了
                log.error("解析token失败!", e);
            }
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
